package com.test.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.test.ssm.pojo.AccountSearch;
import com.test.ssm.pojo.AccountType;
import com.test.ssm.pojo.PublicAccount;
import com.test.ssm.service.AccountService;
import com.test.ssm.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author 徒有琴
 */
@Controller
public class AccountController {
    @Autowired
    private TypeService typeService;

    @Autowired
    private AccountService accountService;

    @RequestMapping("types")
    @ResponseBody
    public List<AccountType> types() {
        return typeService.getAllType();
    }

    @RequestMapping("search")
    @ResponseBody
    public PageInfo<PublicAccount> index(AccountSearch accountSearch, Integer pageNum) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        return accountService.getAccount(accountSearch, pageNum, 2);
    }

    @RequestMapping("info")
    @ResponseBody
    public PublicAccount goUpdate(Integer id) {
        return accountService.getAccountById(id);
    }

    @RequestMapping("edit")
    public String edit(PublicAccount publicAccount) {
        if (publicAccount.getId() != null) {
            accountService.updateAccount(publicAccount);
        }else{
            accountService.addAccount(publicAccount);
        }
        return "redirect:index.html";
    }
    @RequestMapping("delete")
    public String delete(Integer id) {
        accountService.deleteAccount(id);
        return "redirect:index.html";
    }
}
